<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Spacebar Server</title>

		<link rel="preconnect" href="https://fonts.googleapis.com" />
		<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
		<link
			href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap"
			rel="stylesheet"
		/>

		<style>
			body {
				font-family: "Montserrat", sans-serif;
				background-color: rgb(10, 10, 10);
				color: white;
				font-size: 1.1rem;
				height: 100vh;
			}

			* {
				padding: 0;
				margin: 0;
			}

			p {
				margin-top: 10px;
			}

			#wordmark {
				width: min(200px, 50%);
				margin: 20px;
				position: absolute;
				top: 20px;
				left: 20px;
			}

			.title {
				font-size: 1.5rem;
				font-weight: 600;
			}

			.subtitle {
				font-size: 1.1rem;
				font-weight: 400;
			}

			.container {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100%;
			}

			.box {
				min-width: 350px;
				width: max(22vw, 350px);
				padding: 32px;
				border-radius: 8px;
				background-color: rgb(32, 32, 32);
				align-items: center;
				display: flex;
				flex-direction: column;
				text-align: center;
			}

			#captcha-container {
				margin: 20px 0;
			}

			.retry-button {
				margin-top: 15px;
				padding: 10px 20px;
				background-color: #5865f2;
				color: white;
				border: none;
				border-radius: 4px;
				cursor: pointer;
				font-family: "Montserrat", sans-serif;
			}

			.retry-button:hover {
				background-color: #4752c4;
			}

			.retry-button:disabled {
				background-color: #666;
				cursor: not-allowed;
			}
		</style>
	</head>

	<body>
		<div class="container">
			<img
				alt="Spacebar Logo"
				id="wordmark"
				src="https://raw.githubusercontent.com/spacebarchat/spacebarchat/master/branding/svg/Spacebar__Logo-Blue.svg"
			/>

			<div class="box">
				<p id="title" class="title">Verifying your email</p>
				<p id="subtitle" class="subtitle">Please wait...</p>
			</div>
		</div>

		<script>
			window.onload = verify;

			let captchaConfig = null;
			let currentToken = null;

			function verify() {
				const title = document.getElementById("title");
				const subtitle = document.getElementById("subtitle");

				// if no fragment identifier in URL, error
				if (!window.location.hash) {
					title.innerText = "Invalid Link";
					subtitle.innerText = "Please check the link and try again.";
					return;
				}

				// convert fragment to a key-value pair
				const fragment = window.location.hash.substring(1);
				const pairs = fragment.split("&");
				const values = {};
				pairs.forEach((pair) => {
					const [key, value] = pair.split("=");
					values[key] = value;
				});

				// ensure token key is present
				if (!values.token) {
					title.innerText = "Invalid Link";
					subtitle.innerText = "Please check the link and try again.";
					return;
				}

				currentToken = values.token;
				performVerification();
			}

			function performVerification(captchaResponse = null) {
				const title = document.getElementById("title");
				const subtitle = document.getElementById("subtitle");

				const requestBody = { token: currentToken };
				if (captchaResponse) {
					requestBody.captcha_key = captchaResponse;
				}

				// make request to server
				fetch("/api/auth/verify", {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
					},
					body: JSON.stringify(requestBody),
				})
					.then((response) => response.json())
					.then((data) => {
						// check for captcha requirement
						if (data.captcha_key && data.captcha_key.includes("captcha-required")) {
							captchaConfig = {
								sitekey: data.captcha_sitekey,
								service: data.captcha_service
							};
							showCaptcha();
							return;
						}

						// check for other error responses
						if ("message" in data) {
							title.innerText = "Email Verification Link Expired";
							subtitle.innerText = "Please request a new verification link.";
							return;
						}

						title.innerText = "Email Verified";
						subtitle.innerText = "You can now login.";
					})
					.catch((error) => {
						title.innerText = "Email Verification Failed";
						subtitle.innerText = error;
					});
			}

			function showCaptcha() {
				const title = document.getElementById("title");
				const subtitle = document.getElementById("subtitle");
				const box = document.querySelector(".box");

				title.innerText = "Please complete the captcha";
				subtitle.innerText = "We need to verify that you're human.";

				// Create captcha container if it doesn't exist
				let captchaContainer = document.getElementById("captcha-container");
				if (!captchaContainer) {
					captchaContainer = document.createElement("div");
					captchaContainer.id = "captcha-container";
					box.appendChild(captchaContainer);
				}

				// Load and render captcha based on service
				if (captchaConfig.service === "hcaptcha") {
					loadHCaptcha();
				} else if (captchaConfig.service === "recaptcha") {
					loadReCaptcha();
				}
			}

			function loadHCaptcha() {
				if (window.hcaptcha) {
					renderHCaptcha();
					return;
				}

				const script = document.createElement("script");
				script.src = "https://js.hcaptcha.com/1/api.js";
				script.onload = renderHCaptcha;
				document.head.appendChild(script);
			}

			function renderHCaptcha() {
				const captchaContainer = document.getElementById("captcha-container");
				captchaContainer.innerHTML = "";

				window.hcaptcha.render(captchaContainer, {
					sitekey: captchaConfig.sitekey,
					theme: "dark",
					callback: function(response) {
						performVerification(response);
					},
					"expired-callback": function() {
						const title = document.getElementById("title");
						const subtitle = document.getElementById("subtitle");
						title.innerText = "Captcha Expired";
						subtitle.innerText = "Please refresh the page and try again.";
					},
					"error-callback": function() {
						const title = document.getElementById("title");
						const subtitle = document.getElementById("subtitle");
						title.innerText = "Captcha Error";
						subtitle.innerText = "Please refresh the page and try again.";
					}
				});
			}

			function loadReCaptcha() {
				if (window.grecaptcha) {
					renderReCaptcha();
					return;
				}

				const script = document.createElement("script");
				script.src = "https://www.google.com/recaptcha/api.js";
				script.onload = renderReCaptcha;
				document.head.appendChild(script);
			}

			function renderReCaptcha() {
				const captchaContainer = document.getElementById("captcha-container");
				captchaContainer.innerHTML = "";

				window.grecaptcha.render(captchaContainer, {
					sitekey: captchaConfig.sitekey,
					theme: "dark",
					callback: function(response) {
						performVerification(response);
					},
					"expired-callback": function() {
						const title = document.getElementById("title");
						const subtitle = document.getElementById("subtitle");
						title.innerText = "Captcha Expired";
						subtitle.innerText = "Please refresh the page and try again.";
					},
					"error-callback": function() {
						const title = document.getElementById("title");
						const subtitle = document.getElementById("subtitle");
						title.innerText = "Captcha Error";
						subtitle.innerText = "Please refresh the page and try again.";
					}
				});
			}
		</script>
	</body>
</html>
